﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Linq
{

    /// <summary>
    /// Linq to object（数组、list集合）--内存里面的数据
    /// linq to sql(查询数据库用的) -- 在数据库数据
    /// linq to xml 查询xml文件
    /// </summary>
    public class LinqShow
    {
        #region 初始化数据
        List<Student> studentList = new List<Student>() {
            new Student(){Id=1,Name="张三",Age=30},
            new Student(){Id=2,Name="李四",Age=40},
            new Student(){Id=3,Name="王五",Age=50},
            new Student(){Id=4,Name="王麻子",Age=18},
            new Student(){Id=5,Name="朝阳",Age=20},
            new Student(){Id=6,Name="飞雪",Age=21},
            new Student(){Id=7,Name="向阳",Age=28},
            new Student(){Id=8,Name="乐乐",Age=28},
            new Student(){Id=9,Name="若依",Age=18},
            new Student(){Id=10,Name="千落",Age=20}
        };
        #endregion

        public void show()
        {
            //List<Student> students = new List<Student>();
            //foreach (var item in studentList)
            //{
            //    if (item.Id < 5)
            //    {
            //        students.Add(item);
            //    }
            //}
            // 自定义linq
            var list = AntWhere(studentList, x => x.Id < 5);
            // 官方的linq(扩展方法方式的)
            var list2 = studentList.Where(x => x.Id < 5).ToList();
            // 表达式方式(这种方式最后生成代码和方法是一样的)
            var list3 = (from s in studentList where s.Id < 5 select s).ToList();
        }

        public List<Student> AntWhere(List<Student> resource,Func<Student,bool> func)
        {
            List<Student> list = new List<Student>();
            foreach (var item in resource)
            {
                if (func(item))
                {
                    list.Add(item);
                }
            }

            return list;
        }
    }

    public class Student
    {
        public int Id { get; set; }

        public string Name { get; set; }
        public int Age { get; set; }
    }
}
